var lr         = require('tiny-lr'),
    server     = lr(),
    gulp       = require('gulp'),
    webserver  = require('gulp-webserver'),
    config     = require('./config.json'),
    gulpOpen   = require('gulp-open'),
    livereload = require('gulp-livereload'),
    os         = require('os'),
    uglify     = require('gulp-uglify');
    concat     = require('gulp-concat');
    sass       = require('gulp-sass'); 


//浏览器判断
var browser = os.platform() === 'linux' ? 'Google chrome' : (
    os.platform() === 'darwin' ? 'Google chrome' : (
    os.platform() === 'win32' ? 'chrome' : 'firefox'));
//开启本地 Web 服务器功能
gulp.task('webserver', function() {
  gulp.src( './serverMarket/' )
    .pipe(webserver({
      host:             config.localserver.host,
      port:             config.localserver.port,
      livereload:       true,
      directoryListing: false
    }));
});

//通过浏览器打开本地 Web服务器 路径
gulp.task('openbrowser', function(done) {
  var url = 'http://' + config.localserver.host + ':' + config.localserver.port;
  gulp.src('./serverMarket/')
      .pipe(gulpOpen({
          app: browser,
          uri: url
      }))
      .on('end', done);
});

//编译Sass
gulp.task('compass', function () {
    gulp.src(['./sass/*.scss'])
        .pipe(sass())
        .pipe(gulp.dest('./serverMarket/css/'));
}); 
// 压缩打包js
// gulp.task('js', function() {
//     gulp.src(['./js/lib/*.min.js','./js/*.js'])
//         .pipe(uglify())
//         .pipe(concat('index.js'))
//         .pipe(gulp.dest('build'));
// });

// gulp.task('js', function() {
//     gulp.src(['./serverMarket/js/test1/*.js'])
//         .pipe(uglify({report: "min"}))
//         .pipe(gulp.dest('./serverMarket/js/test2'));
// });


gulp.task('js', function() {
    gulp.src(['./serverMarket/js/lib/jquery-2.1.1.min.js','./serverMarket/js/lib/hammer.min.js','./serverMarket/js/lib/jquery.hammer.js'])
        .pipe(uglify())
        .pipe(concat('lib.js'))
        .pipe(gulp.dest('./serverMarket/js/build'));
});
//文件监控
gulp.task('watch', function () {

  server.listen(35729, function (err) {
    if (err){
      return console.log(err);
    }
  });
 
  gulp.watch(['./serverMarket/*.html','./serverMarket/*.php','./serverMarket/css/*.css','./serverMarket/js/dev/*.js'],  function (e) {
    server.changed({
      body: {
        files: [e.path]
      }
    });
  });

  gulp.watch(['./sass/*.scss'], function (e) {
    gulp.run('compass');
  });

  // gulp.watch(['./serverMarket/js/*.js'], function (e) {
  //   gulp.run('js');
  // });

  gulp.watch(['./serverMarket/css/*.css'], function (e) {
    server.changed({
      body: {
        files: [e.path]
      }
    });
  });
 
});
 

//默认任务
gulp.task('default', function(){
  console.log('Starting Gulp tasks, enjoy coding!');
  gulp.run('compass');
  // gulp.run('js');
  gulp.run('watch');
  gulp.run('webserver');
  gulp.run('openbrowser');
});

